package com.yxjx.duoxue.customview;

import java.util.ArrayList;

import com.yxjx.duoxue.R;
import com.yxjx.duoxue.utils.UIHelper;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

public class YxTabHost extends LinearLayout {

	int[] ids = new int[] { R.id.tab1, R.id.tab2, R.id.tab3 };

	String[] mLabels = new String[] { "课程详情", "教学成果", "老师信息" };

	private int mIndex = -1;

	ArrayList<View> children = new ArrayList<View>();

	public YxTabHost(Context context, AttributeSet attrs) {
		super(context, attrs);
		View ret = LayoutInflater.from(context).inflate(
				R.layout.segment_tab_host, this, true);
		customizeLabelsInternal(ret);
		setTab(0);
	}

	private void customizeLabelsInternal(View ret) {
		for (int i = 0; i < ids.length; i++) {
			View child = ret.findViewById(ids[i]);
			child.setClickable(true);
			UIHelper.setText(child, R.id.text, mLabels[i]);
			children.add(child);
			child.setOnClickListener(mClickLisetner);
		}
	}
	
	public void customizeLabels(String[] labels) {
		this.mLabels = labels;
		customizeLabelsInternal(this);
	}
	
	public void customizeLabelsAndIds(String[] labels, int[] ids) {
		this.mLabels = labels;
		this.ids = ids;
		// walk round
		if (ids.length == 2) {
			findViewById(R.id.tab3).setVisibility(View.GONE);
		}
		customizeLabelsInternal(this);
	}

	public void setTab(int index) {
		if (index < 0 || index > ids.length) {
			return;
		}
		if (mIndex < -1 || mIndex > ids.length) {
			return;
		}
		
		if (mIndex != index) {
			if (mIndex != -1) {
				children.get(mIndex).setSelected(false);
			}
			
			mIndex = index;
			children.get(mIndex).setSelected(true);
			if (mCallback != null) {
				mCallback.tabSelected(mIndex);
			}
		}
	}

	public Callback getCallback() {
		return mCallback;
	}

	public void setCallback(Callback mCallback) {
		this.mCallback = mCallback;
	}

	private View.OnClickListener mClickLisetner = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tab1:
				setTab(0);
				break;
			case R.id.tab2:
				setTab(1);
				break;
			case R.id.tab3:
				setTab(2);
				break;
			default:
				break;
			}

		}
	};
	
	public interface Callback {
		void tabSelected(int index);
	}
	
	private Callback mCallback;
	
}
